/*
 * DprKeyboard.cpp
 *
 *  Created on: 2012-11-28
 *      Author: kylin
 */

#include <fcntl.h>
#include "DprKeyboard.h"
#include "gtype.h"

//////////////////////////////////////////////////////////////////////
// class DprKeyboard
DprKeyboard::DprKeyboard(const QString &devNode)
 : m_devNode(devNode)
{
	m_fd=-1;
}

DprKeyboard::~DprKeyboard()
{
}

bool DprKeyboard::open()
{
	m_fd=::open(m_devNode.toAscii().data(),O_RDONLY);
	if(m_fd==-1)
		return false;

	return true;
}

void DprKeyboard::close()
{
	if(m_fd!=-1)
	{
		::close(m_fd);
		m_fd=-1;
	}
}

bool DprKeyboard::readKey(unsigned short &keyCode,unsigned int wait)
{
	fd_set readfd;
	struct timeval tv;
	int recvLen=0;
	char recvBuf[2];
	int ret;

	tv.tv_sec=wait/1000;
	tv.tv_usec=wait%1000;

	FD_ZERO(&readfd);
	FD_SET(m_fd,&readfd);

	ret=::select(m_fd+1,&readfd,NULL,NULL,&tv);

	switch(ret)
	{
		case -1:
		case 0:
			return false;

		default:
		{
			recvLen=::read(m_fd,recvBuf,1);
			if(recvLen!=1)
				return false;

			keyCode=recvBuf[0];
			return true;
		}
	}
}

//////////////////////////////////////////////////////////////////////
// class KeyboardManager
KeyboardManager::KeyboardManager(const QString &devNode)
{
	m_keyboard=new DprKeyboard(devNode);
}

KeyboardManager::~KeyboardManager()
{
	delete m_keyboard;
}

void KeyboardManager::run()
{
	if(!m_keyboard->open())
	{
		setStarted(false);
		return;
	}

	setStarted(true);
	unsigned short keyCode=keyNone;
	while(true)
	{
		if(needExit())
		{
			setStarted(false);
			break;
		}

		keyCode=keyNone;
		if(m_keyboard->readKey(keyCode,50))
		{
			if(keyCode!=keyNone)
			{
//				qWarning()<<keyCode;
				emit sigKeyEvent(keyCode);
			}
		}
	}

	setStarted(false);
	m_keyboard->close();
}
